﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Servico;
using System.Security.Cryptography;
using System.Text;

public partial class MasterPage : System.Web.UI.MasterPage
{
    Service1 servico = new Service1();

    protected void Page_Load(object sender, EventArgs e)
    {
        // Se estiver autenticado
        if (Session["Email"] != null)
        {
            LabelEmail.Text = Session["Email"].ToString();
            LoginTable.Visible = false;
            LogoutTable.Visible = true;
        }
        else
        {
            LogoutTable.Visible = false;
            LoginTable.Visible = true;
        }
    }

    protected void ButtonLogout_Click(object sender, EventArgs e)
    {
        // TODO nao funciona no registar cliente
        Session.Abandon();
        Session.RemoveAll();
        //Session["Email"] = null;
        Response.Redirect("Home.aspx");
    }

    protected void LoginButton_Click(object sender, EventArgs e)
    {
        // Se o email do cliente for válido então não existe na base de dados
        if (!servico.validarEmailCliente(tbE.Text))
        {//  TODO descomentar quando puder testar MD5
            //Response.Write(getMd5Hash(tbP.Text));
            if (servico.autenticarCliente(tbE.Text, getMd5Hash(tbP.Text)))
            //if (servico.autenticarCliente(tbE.Text, tbP.Text))
            {
                Session["Email"] = tbE.Text;
                Session["Nivel"] = null;
                Response.Redirect("InfoCliente.aspx");
            }
            else
            {
                Session["Erro"] = "Password inválida!";
            }
        }
        // Se o email do funcionario for válido então não existe na base de dados
        else if (!servico.validarEmailFuncionario(tbE.Text))
        {
            //if (servico.autenticarFuncionario(tbE.Text, getMd5Hash(tbP.Text)))
            if (servico.autenticarFuncionario(tbE.Text, getMd5Hash(tbP.Text)))
            {
                Session["Email"] = tbE.Text;
                Session["Nivel"] = servico.nivelFuncionario(tbE.Text).ToString();
                if (Session["Nivel"].Equals("6"))
                    Response.Redirect("SubmeterPedido.aspx");
                else
                    Response.Redirect("ConsultarPlaneamentoPessoal.aspx");
            }
            else
            {
                Session["Erro"] = "Password inválida!";
            }
        }
        else
        {
            Session["Erro"] = "Email inválido!";
        }

        MensagemErro();
    }

    // Hash an input string and return the hash as
    // a 32 character hexadecimal string.
    public string getMd5Hash(string input)
    {
        // Create a new instance of the MD5CryptoServiceProvider object.
        MD5 md5Hasher = MD5.Create();

        // Convert the input string to a byte array and compute the hash.
        byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

        // Create a new Stringbuilder to collect the bytes
        // and create a string.
        StringBuilder sBuilder = new StringBuilder();

        // Loop through each byte of the hashed data 
        // and format each one as a hexadecimal string.
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("x2"));
        }

        // Return the hexadecimal string.
        return sBuilder.ToString();
    }

    protected void MensagemErro()
    {
        Panel panel = (Panel)ContentPlaceHolder1.FindControl("PanelMsg"); 

        if (Session["Erro"] != null)
        {
            Literal lit = new Literal();
            lit.Text = "<ul id=\"menu2\"><li>" + Session["Erro"].ToString() + "</li></ul>";
            panel.Controls.Add(lit);
            Session["Erro"] = null;
        }
        if (Session["Sucesso"] != null)
        {
            Literal lit = new Literal();
            lit.Text = "<ul id=\"menu3\"><li>" + Session["Sucesso"].ToString() + "</li></ul>";
            panel.Controls.Add(lit);
            Session["Sucesso"] = null;
        }
    }
}
